package cn.edu.bjfu.practice.practice.manager.service.impl;

import cn.edu.bjfu.practice.practice.app.component.MD5util;
import cn.edu.bjfu.practice.practice.manager.dao.TeacherDao;
import cn.edu.bjfu.practice.practice.manager.dao.UserTableDao;
import cn.edu.bjfu.practice.practice.manager.pojo.domain.Teacher;
import cn.edu.bjfu.practice.practice.manager.pojo.domain.UserTable;
import cn.edu.bjfu.practice.practice.manager.pojo.query.AddTeacherForm;
import cn.edu.bjfu.practice.practice.manager.pojo.query.LoginForm;
import cn.edu.bjfu.practice.practice.manager.pojo.query.ModifyTeacherForm;
import cn.edu.bjfu.practice.practice.manager.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Service
public class ManagerServiceImpl implements ManagerService {


    @Autowired
    UserTableDao userTableDao;

    @Autowired
    TeacherDao teacherDao;

    @Override
    public UserTable login(LoginForm loginForm, HttpSession session, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", loginForm.getId());
        map.put("password", MD5util.encode(loginForm.getPassword()));
        List<UserTable> userList =userTableDao.selectByMap(map);

        if(userList.size() > 0) {
            session.setAttribute("user", userList.get(0));
            return userList.get(0);
        }
        else {
            session.setAttribute("user", null);
            return new UserTable();
        }
    }

    @Override
    public void addTeacher(AddTeacherForm addTeacherForm) {

        UserTable userTable = new UserTable();
        userTable.setPassword(MD5util.encode("123456"));
        userTable.setType(1);
        userTableDao.insert(userTable);

        Teacher teacher = new Teacher();
        teacher.setId(userTable.getId());
        teacher.setName(addTeacherForm.getName());
        teacher.setEmail(addTeacherForm.getEmail());
        teacherDao.insert(teacher);
    }

    @Override
    public void modifyTeacher(ModifyTeacherForm modifyTeacherForm) {
        Teacher teacher = new Teacher();
        teacher.setId(modifyTeacherForm.getId());
        teacher.setName(modifyTeacherForm.getName());
        teacher.setPhone(modifyTeacherForm.getPhone());
        teacher.setEmail(modifyTeacherForm.getEmail());
        teacherDao.updateById(teacher);
    }

    @Override
    public List<Teacher> selectTeacher() {
        return teacherDao.selectByMap(new HashMap<>());
    }
}
